﻿using System;
using System.Text;
using System.IO;
using System.Data;
using System.Collections.Generic;
using mklib.json;

namespace mklib
{
	public static class JSON
	{
		public static IJsonValue Parse(string s)
		{
			StringBuilder b = new StringBuilder(s);
			var reader = new JsonTokenReader (b);
			var ss = reader.Parse();
			return ss;
		}
		public static IJsonValue Parse(Stream stream, Encoding enc)
		{
			string s;
			using (StreamReader reader = new StreamReader (stream, enc)) {
				s = reader.ReadToEnd ();
			}
			return Parse (s);
		}
		public static IJsonValue Parse(Stream stream)
		{
			return Parse (stream, Encoding.UTF8);
		}

		public static string Stringify(IJsonValue val, bool format)
		{
			JsonStringifySetting setting = new JsonStringifySetting ();
			if (!format) {
				setting.NewLine = String.Empty;
				setting.Indent = String.Empty;
				setting.ValueBefore = String.Empty;
			}
			return setting.Convert (val);
		}
		public static string Stringify(IJsonValue val)
		{
			return Stringify (val, false);
		}

		public static string Stringify(DataTable dt, JsonDataParseType type, bool format)
		{
			IJsonValue val = DataToJson.Convert (dt, 0, type);
			return Stringify (val, format);
		}
		public static string Stringify(DataTable dt, bool format)
		{
			return Stringify (dt, JsonDataParseType.Data, format);
		}
		public static string Stringify(DataTable dt, JsonDataParseType type)
		{
			return Stringify (dt, type, false);
		}
		public static string Stringify(DataTable dt)
		{
			return Stringify (dt, JsonDataParseType.Data, false);
		}

		public static DataTable ParseData(IJsonValue json)
		{
			Dictionary<string, object> DATA = json.ValueOf () as Dictionary<string, object>;
			if (DATA == null)
				return null;

			if (!DATA.ContainsKey ("schema") || !DATA.ContainsKey ("data"))
				return null;

			Dictionary<string, object> schema = DATA ["schema"] as Dictionary<string, object>;
			object[] data = DATA["data"] as object[];

			if (schema == null || data == null)
				return null;

			DataTable dt = new DataTable ();
			foreach (string key in schema.Keys) {
				dt.Columns.Add (key, Type.GetType (schema [key].ToString ()));
			}
			foreach(Dictionary<string, object> ROW in data)
			{
				DataRow row = dt.NewRow ();
				foreach (string key in ROW.Keys) {
					row [key] = JsonHelper.ConvertValue (ROW [key], dt.Columns [key].DataType);
				}
				dt.Rows.Add (row);
			}

			return dt;
		}

		public static DataTable ParseData(string s)
		{
			IJsonValue json = Parse (s);
			return ParseData (json);
		}

	}
}

